package tmt.usercenter.web.plugin.editormodel;

import com.tmt.datatable.editor.ext.fileinfo.IFileInfoFinder;
import com.tmt.datatable.model.FileInfo;
import com.tmt.fileservice.IFileService;
import com.tmt.helper.ReflectHelper;
import com.tmt.jpafieldvalueconvert.JpaFieldValueConvert;
import com.tmt.jpafieldvalueconvert.impl.FileUrlFieldConverter;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ThreeManTeam on 2017/6/7.
 */
public class FileInfoFinder implements IFileInfoFinder {

    private IFileService fileService;

    public FileInfoFinder(IFileService fileService){
        this.fileService = fileService;
    }

    @Override
    public <T> List<Field> getFileFieldList(T obj) {
        List<Field> list = new ArrayList<>();
        List<Field> fieldList = ReflectHelper.findAllFieldByAnnotation(obj.getClass(), JpaFieldValueConvert.class, -1);
        fieldList.stream().forEach(x -> {
            JpaFieldValueConvert annotation = x.getAnnotation(JpaFieldValueConvert.class);
            Class clazz = annotation.converter();
            if (clazz == FileUrlFieldConverter.class)
                list.add(x);
        });
        return list;
    }

    @Override
    public <T> FileInfo getFileInfo(T obj, Field field, String fileId) {
        JpaFieldValueConvert annotation = field.getAnnotation(JpaFieldValueConvert.class);
        String displayName = annotation.displayName();
        if (StringUtils.isEmpty(displayName)) {
            String displayNameColumn = annotation.displayNameColumn();
            if (StringUtils.isEmpty(displayNameColumn))
                displayNameColumn = field.getName();
            displayName = ReflectHelper.getFieldValue(obj, displayNameColumn).toString();
        }

        String fileUrl = ReflectHelper.getFieldValue(obj, field.getName()).toString();
        String filePath = fileService.getFileDispatcher().fileUrlToPath(fileUrl);
        String[] fileNames = fileService.getFileDispatcher().getFileName(filePath);
        long len = fileService.getFileSize(filePath);
        String id = StringUtils.isEmpty(fileId) ? fileUrl : fileId;

        FileInfo fi = new FileInfo();
        fi.setId(id);
        fi.setFileName(fileNames[0] + "." + fileNames[1]);
        fi.setDisplayName(displayName);
        fi.setFileSize(len);
        fi.setSystemPath(filePath);
        fi.setWebPath(fileUrl);
        return fi;
    }

}
